//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;

namespace Microsoft.Research.ScientificWorkflow.Activities
{
    [Name("Web Page Source Downloader", "Web Page Source")]
    [Description("Loads the text source of a web page identified by a target URI")]
    [WorkflowCategory("Web")]
    public partial class WebPageSourceDownload : System.Workflow.ComponentModel.Activity
    {
        #region Property Definitions
        // Required input property
        public static DependencyProperty SourceUriProperty =
            DependencyProperty.Register("SourceUri", typeof(Uri), typeof(WebPageSourceDownload));
        // Output property
        public static DependencyProperty PageResultProperty =
            DependencyProperty.Register("PageResult", typeof(string), typeof(WebPageSourceDownload));

        [RequiredInputParam]
        [ValidationOption(ValidationOption.Required)]
        [Name("Source URI", "URI")]
        [Description("The source URI provides the location from which to download the web page contents")]
        public Uri SourceUri
        {
            get { return ((Uri)(base.GetValue(WebPageSourceDownload.SourceUriProperty))); }
            set { base.SetValue(WebPageSourceDownload.SourceUriProperty, value); }
        }

        [OutputParam]
        [Name("Source Text", "Source")]
        [Description("The source text of the retrieved web page")]
        public string PageResult
        {
            get { return ((string)(base.GetValue(WebPageSourceDownload.PageResultProperty))); }
            set { base.SetValue(WebPageSourceDownload.PageResultProperty, value); }
        }
        #endregion

        public WebPageSourceDownload()
		{
			InitializeComponent();
		}

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            WebRequest webReq = HttpWebRequest.Create(SourceUri);
            WebResponse webResp = webReq.GetResponse();
            StreamReader sr = new StreamReader(webResp.GetResponseStream());
            PageResult = sr.ReadToEnd();
            sr.Close();
            webResp.Close();

            Console.WriteLine("Activity Executed!\n{0}", PageResult);

            return base.Execute(executionContext);
        }
	}
}
